package com.lancoo.answer.ui.child.training;

import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.lzyzsd.circleprogress.DonutProgress;
import com.lancoo.answer.R;
import com.lancoo.answer.manager.MediaManager;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.entity.wordSpell.WordKeyDetailBean;
import com.lancoo.answer.model.entity.wordSpell.WordListenWriteChild;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;
import com.lancoo.answer.view.adapter.wordSpell.InputKeyBoardAdapter;
import com.lancoo.answer.view.adapter.wordSpell.WordSpellAnswerAdapter;
import com.lancoo.answer.helper.ToastHelper;
import com.rxjava.rxlife.RxLife;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/1 20:53
 * Description:词汇听写
 */
public class ChildWordListenWriteAnswerFragment extends Fragment implements View.OnClickListener{

    private static final String TAG = "ChildWordListenWriteAns";
    private final int mColorProgressDim=0xffededed;
    private final int mColorProgressPlay=0xff2ac8ef;
    private long clickTime;
    private WordListenWriteChild wordListenWriteChild;
    private Item item;
    private ImageView mImgAudio;
    private WordSpellAnswerAdapter answerAdapter;
    private InputKeyBoardAdapter inputAdapter;
    private ImageView mImgDelete;
    private int enableAnwer;
    private final int totalPlayTimes=2;
    private int currentPlayTimes=0;
    private MediaManager mediaManager;
    private DonutProgress mDonutProgress;
    private Disposable disposable,nextPlayDisposebal;
    private int queseIndex=-1;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ev_fragment_answer_word_listen_write, container, false);
    }


    /**
     *
     * @param kindIndex List<Type>题型下标
     * @param queseIndex List<Type>大题下标
     * @param smallQueseIndex List<Type>小题下标
     * @return fragment
     */
    public static Fragment loadChildFragment(int kindIndex, int queseIndex,
                                             int smallQueseIndex){
        ChildWordListenWriteAnswerFragment queseFragment=new ChildWordListenWriteAnswerFragment();
        Bundle mBundle=new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX,kindIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX,queseIndex);
        mBundle.putInt(AnswerConstant.KEY_CHILDINDEX,smallQueseIndex);
        queseFragment.setArguments(mBundle);
        return queseFragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        initView(view);
    }

    private void initData(){
        if(getArguments()==null||getContext()==null){
            return;
        }
        mediaManager=new MediaManager(getContext());
        startAudioPlay();
        int kindIndex=getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        queseIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        int smallQueseIndex=getArguments().getInt(AnswerConstant.KEY_CHILDINDEX);
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        enableAnwer = ConstantBean.Companion.getTaskControlBean().getEnableAnwer();
        Child child = kindBeanListk.get(kindIndex).getQuesList()
                .get(queseIndex).getChildList().get(smallQueseIndex);
        item = child.getItemList().get(0);
        List<WordListenWriteChild> wordListenSpellList =
                ConstantBean.Companion.getWordListenSpellList();
        wordListenWriteChild = wordListenSpellList.get(queseIndex);
        List<WordKeyDetailBean> inputWordKeys = wordListenWriteChild.getInputWordKeys();
        for (WordKeyDetailBean bean:inputWordKeys){
            bean.setEnable(enableAnwer ==1);
        }
    }

    private void initView(View view){
        mDonutProgress = view.findViewById(R.id.mProgress);
        mImgAudio = view.findViewById(R.id.mImgAudio);
        mImgAudio.setOnClickListener(this);
        mImgAudio.setImageResource(enableAnwer==0?R.mipmap.ev_ic_word_audio_disable:R.drawable.ev_volume_blue_gif);
        answerAdapter = new WordSpellAnswerAdapter(wordListenWriteChild.getAnswerWordKeys());
        RecyclerView answerRv=view.findViewById(R.id.mRecyclerViewAnswer);
        answerRv.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.HORIZONTAL,false));
        answerRv.setAdapter(answerAdapter);
        inputAdapter = new InputKeyBoardAdapter(wordListenWriteChild.getInputWordKeys());
        RecyclerView inputRv=view.findViewById(R.id.mRecyclerViewInputKey);
        inputRv.setLayoutManager(new GridLayoutManager(getContext(),4,GridLayoutManager.VERTICAL,false));
        inputRv.setAdapter(inputAdapter);
        mImgDelete = view.findViewById(R.id.mImgDelete);
        mImgDelete.setOnClickListener(this);
        setDeleteImg();
        inputAdapter.setOnInputClickCallBack(new InputKeyBoardAdapter.OnInputClickCallBack() {
            @Override
            public void onInputClick(int position) {
                super.onInputClick(position);
                if(position<0||position>=wordListenWriteChild.getInputWordKeys().size()||
                        System.currentTimeMillis()-clickTime<200){
                    return;
                }
                TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
                if(taskControlBean.getEnableAnwer()==0){
                    return;
                }
                clickTime=System.currentTimeMillis();
                List<WordKeyDetailBean> inputWordKeys = wordListenWriteChild.getInputWordKeys();
                WordKeyDetailBean wordKeyDetailBean = inputWordKeys.get(position);
                if(position==inputWordKeys.size()-1) {
                    //作答结束，进入下一个大题
                    FragmentCommunicationUtils.autoNextQuesFragment(ChildWordListenWriteAnswerFragment.this,false);
                    return;
                }
                if(wordKeyDetailBean.isSelected()){
                    return;
                }

                List<WordKeyDetailBean> answerWordKeys = wordListenWriteChild.getAnswerWordKeys();
                if(!TextUtils.isEmpty(answerWordKeys.get(answerWordKeys.size()-1).getKeyStr())){
                    return;
                }
                wordKeyDetailBean.setSelected(true);
                boolean isFill=true;
                for (WordKeyDetailBean bean:answerWordKeys){
                    if(TextUtils.isEmpty(bean.getKeyStr())){
                        bean.setKeyStr(wordKeyDetailBean.getKeyStr());
                        isFill=false;
                        break;
                    }
                }
                if(isFill){
                    return;
                }
                answerAdapter.notifyDataSetChanged();
                inputAdapter.notifyDataSetChanged();
                updateAnswer();
                Log.e(TAG,"keyStr:"+wordKeyDetailBean.getKeyStr());
            }
        });
    }

    private void setDeleteImg(){
        List<WordKeyDetailBean> answerWordKeys =
                wordListenWriteChild.getAnswerWordKeys();
        boolean enable=false;
        for (WordKeyDetailBean detailBean:answerWordKeys){
            if(!TextUtils.isEmpty(detailBean.getKeyStr())){
                enable=true;
                break;
            }
        }
        mImgDelete.setImageResource(enable||enableAnwer==0?R.mipmap.ev_ic_word_delete_disable:
                R.mipmap.ev_ic_word_delete_enable);
    }


    /**
     * 界面由不可作答变成可作答
     */
    public void onTrainEnable() {
        Log.e("词汇听写","进来拉onTrainEnable");
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        enableAnwer = taskControlBean.getEnableAnwer();
        if(wordListenWriteChild==null){
            return;
        }
        if(enableAnwer==0){
            return;
        }
        List<WordKeyDetailBean> inputWordKeys = wordListenWriteChild.getInputWordKeys();
        for (WordKeyDetailBean bean:inputWordKeys){
            bean.setEnable(true);
        }
        setDeleteImg();

        inputAdapter.notifyDataSetChanged();
        mImgAudio.setImageResource(R.drawable.ev_volume_blue_gif);
        mDonutProgress.setUnfinishedStrokeColor(mColorProgressDim);
        mDonutProgress.setFinishedStrokeColor(mColorProgressPlay);
        Log.e("词汇听写","ui更新了");
    }

    public void autoPlayAudio(){
        startAudioPlay();
    }

    @Override
    public void onClick(View v) {
        if(System.currentTimeMillis()-clickTime<500){
            return;
        }
        clickTime=System.currentTimeMillis();
        int id=v.getId();
        if(id==R.id.mImgDelete){
            onDelteAnswer();
        }else if(id==R.id.mImgAudio){
            onPause();
            bindInterval();
            startAudioPlay();
        }
    }

    private void onDelteAnswer(){
        if(enableAnwer==0){
            return;
        }
        List<WordKeyDetailBean> answerWordKeys = wordListenWriteChild.getAnswerWordKeys();
        for (int i = answerWordKeys.size()-1; i >=0; i--) {
            WordKeyDetailBean wordKeyDetailBean = answerWordKeys.get(i);
            if(!TextUtils.isEmpty(wordKeyDetailBean.getKeyStr())){
                String keyStr = wordKeyDetailBean.getKeyStr();
                wordKeyDetailBean.setKeyStr("");
                List<WordKeyDetailBean> inputWordKeys = wordListenWriteChild.getInputWordKeys();
                for (WordKeyDetailBean input:inputWordKeys){
                    if(TextUtils.equals(keyStr,input.getKeyStr())&&input.isSelected()){
                        input.setSelected(false);
                        break;
                    }
                }
                break;
            }
        }
        inputAdapter.notifyDataSetChanged();
        answerAdapter.notifyDataSetChanged();
        updateAnswer();
    }

    @Override
    public void onPause() {
        super.onPause();
        if(mediaManager!=null){
            mediaManager.seekTo(0);
            mediaManager.pause();
        }
        if(disposable!=null){
            disposable.dispose();
        }
        if(nextPlayDisposebal!=null){
            nextPlayDisposebal.dispose();
        }
        resetProgress();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(mediaManager!=null){
            mediaManager.release();
            mediaManager=null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume: "+queseIndex );
        bindInterval();
    }

    private void startAudioPlay(){
        Log.e(TAG,"startAudioPlay 开始音频播放 "+queseIndex);
        if(mediaManager==null||wordListenWriteChild==null||queseIndex==-1){
            return;
        }
        Log.e(TAG,"startAudioPlay 开始音频播放 111");
        if(enableAnwer==0){
            return;
        }
        Log.e(TAG,"startAudioPlay 开始音频播放 2222");
        if(mDonutProgress==null){
            return;
        }
        Log.e(TAG,"startAudioPlay 开始音频播放 3333");
        String audioUrl = wordListenWriteChild.getAudioUrl();
        if(TextUtils.isEmpty(audioUrl)){
            return;
        }
        mediaManager.setPlaySpeed(0.85f);
        mediaManager.setUpMedia(audioUrl, new MediaManager.OnPlayListener() {
            @Override
            public void onComplete() {
                currentPlayTimes++;
                if(currentPlayTimes==totalPlayTimes){
                    resetProgress();
                }else{
                    if(nextPlayDisposebal!=null){
                        nextPlayDisposebal.dispose();
                    }
                    nextPlayDisposebal=Flowable
                        .timer(500, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .as(RxLife.as(ChildWordListenWriteAnswerFragment.this, Lifecycle.Event.ON_PAUSE))
                        .subscribe(aLong -> {
                            mediaManager.seekTo(0);
                            mediaManager.start();
                        });

                }
            }

            @Override
            public void onStartError() {
                ToastHelper.showAudioLoadErrorToast(getContext());
            }

            @Override
            public void onPausePlay() {

            }

            @Override
            public void onSourceError() {
                ToastHelper.showAudioLoadErrorToast(getContext());
            }

            @Override
            public void onStopPlay() {

            }

            @Override
            public void onPrepare() {
                mediaManager.start();
                if(mImgAudio!=null){
                    AnimationDrawable animation = (AnimationDrawable) mImgAudio.getDrawable();
                    animation.start();
                }
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {

            }
        });

    }

    private void bindInterval() {
        if(disposable!=null){
            disposable.dispose();
        }
        disposable = Flowable
            .interval(0, 30L, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .as(RxLife.as(this,Lifecycle.Event.ON_PAUSE))
            .subscribe(new Consumer<Long>() {
                @Override
                public void accept(Long aLong) throws Exception {
                    if(mediaManager==null||!mediaManager.isPrepared()||mDonutProgress==null){
                        return;
                    }
                    int currentPosition = mediaManager.getCurrentPosition();
                    int during = mediaManager.getDuring();
                    int pecent=currentPosition*100/during;
                    mDonutProgress.setProgress(pecent);

                }
            });

        if(ConstantBean.Companion.getTaskControlBean().isTraining()){
            startAudioPlay();
        }
    }

    private void resetProgress(){
        if(mDonutProgress==null){
            return;
        }
        mDonutProgress.setProgress(0);
        currentPlayTimes=0;
        if(mImgAudio!=null){
            mImgAudio.clearAnimation();
            mImgAudio.setImageResource(enableAnwer==0?R.mipmap.ev_ic_word_audio_disable:R.drawable.ev_volume_blue_gif);

        }
    }

    private void updateAnswer(){
        if(item==null){
            return;
        }
        Flowable.timer(0,TimeUnit.MILLISECONDS).observeOn(Schedulers.io())
                .as(RxLife.as(ChildWordListenWriteAnswerFragment.this))
                .subscribe(aLong -> {
                    List<WordKeyDetailBean> answerWordKeys = wordListenWriteChild.getAnswerWordKeys();
                    StringBuilder stringBuilder=new StringBuilder();
                    List<String> answerList=new ArrayList<>();
                    for (WordKeyDetailBean bean:answerWordKeys){
                        if(!TextUtils.isEmpty(bean.getKeyStr())){
                            stringBuilder.append(bean.getKeyStr());
                            stringBuilder.append(bean.isNextSpace()?" ":"");
                            answerList.add(bean.getKeyStr().trim());
                        }
                    }
                    item.setStuAnswer(stringBuilder.toString().trim());
                    item.setSelectedKeyBoards(answerList);
                });
    }

    /**
     * 暂停小题音频播放
     */
    public void pauseChildAudioPlay(){
        Log.e("词汇听写","暂停小题音频播放");
        onPause();
    }



}
